package linkedList.双指针;

import linkedList.BaseLinkedListTest;
import po.ListNode;

/**
 * @author songZiHao
 * @version 1.0.0
 * @ClassName 交换链表中的节点1721.java
 * @Description https://leetcode-cn.com/problems/swapping-nodes-in-a-linked-list/
 * @createTime 2021年03月20日 11:10:00
 */
public class 交换链表中的节点1721 extends BaseLinkedListTest {
    /**
     * 链表正数第 k 个节点和倒数第 k 个节点的值后，返回链表的头节点（链表 从 1 开始索引）
     * todo 主要这里只需要交换节点的值就可以了，因为交换的是节点，而不是交换的顺序
     */
    public static ListNode swapNodes(ListNode head, int k) {
        if (head.next == null) {
            return head;
        }
        ListNode pre = new ListNode(0, head);
        ListNode fastPoint = pre, slowPoint = pre, temp = pre;
        for (int i = 0; i < k; i++) {
            temp = temp.next;
            fastPoint = fastPoint.next;
        }
        while (fastPoint != null) {
            slowPoint = slowPoint.next;
            fastPoint = fastPoint.next;
        }
        int val = temp.val;
        temp.val = slowPoint.val;
        slowPoint.val = val;
        return pre.next;
    }

    public static void main(String[] args) {
        swapNodes(createLinkedList(1, 2, 3, 4, 5), 2);
    }
}
